package wechat

import (
	"anban/models"
	"anban/service"
	"encoding/xml"
	"fmt"
	"net/url"
	"strings"
	"time"
)

// 微信发送过来的事件消息
type EventMsg struct {
	XMLName      xml.Name `xml:"xml"`          // XML根节点名字
	ToUserName   string   `xml:"ToUserName"`   // 公众号原始ID
	FromUserName string   `xml:"FromUserName"` // 用户openid
	CreateTime   int      `xml:"CreateTime"`   // 微信发消息的时间
	MsgType      string   `xml:"MsgType"`      // 消息类型，事件消息为event
	Event        string   `xml:"Event"`        // 事件类型，如用户关注、取消关注事件

	EventKey string `xml:"EventKey"` // 用户扫描带参数二维码时携带的参数
	Ticket   string `xml:"Ticket"`   // 二维码的ticket，可用来换取二维码图片

	Content string `xml:"Content"` // 用户文字消息内容

	PicUrl  string `xml:"PicUrl"`  // 用户图片消息的图片链接
	MediaId string `xml:"MediaId"` // 图片消息媒体id，可以调用获取临时素材接口拉取数据

	MsgId int64 `xml:"MsgId"` // 用户消息ID

	Latitude  float64 `xml:"Latitude"`  // 上报地理位置事件，位置纬度
	Longitude float64 `xml:"Longitude"` // 上报地理位置事件，位置经度
	Precision float64 `xml:"Precision"` // 上报地理位置事件，位置精度
}

// 处理用户关注公众号事件
func (e *EventMsg) HandleSubscribe() string {
	var input url.Values
	var p map[string]interface{}
	inviteUser := &models.User{}
	if len(e.EventKey) > 0 {
		if strings.Contains(e.EventKey, "inviteparent") {
			params := strings.Split(e.EventKey, "_")
			p = map[string]interface{}{}
			p["id"] = params[2]
			inviteUser = service.GetUserInfo(p)
		}
	}
	wechatUserInfo := GetWechatUserInfo("anban", e.FromUserName)
	if len(wechatUserInfo.Nickname) > 0 {
		p = map[string]interface{}{}
		p["openId"] = wechatUserInfo.Openid
		user := service.GetUserInfo(p)
		if user.Id > 0 {
			input = url.Values{
				"id":               {fmt.Sprintf("%d", user.Id)},
				"union_id":         {wechatUserInfo.Unionid},
				"nick_name":        {wechatUserInfo.Nickname},
				"head_img_url":     {wechatUserInfo.Headimgurl},
				"subscribe_status": {"1"},
				"subscribe_time":   {time.Unix(wechatUserInfo.SubscribeTime, 0).Format("2006-01-02 15:04:05")},
			}
			if inviteUser.Id > 0 {
				input["invite_user_id"] = []string{fmt.Sprintf("%d", inviteUser.Id)}
				input["family_sn"] = []string{inviteUser.FamilySn}
			}
			service.EditUser(input)
		} else {
			input = url.Values{
				"family_sn":        {inviteUser.FamilySn},
				"open_id":          {wechatUserInfo.Openid},
				"union_id":         {wechatUserInfo.Unionid},
				"nick_name":        {wechatUserInfo.Nickname},
				"head_img_url":     {wechatUserInfo.Headimgurl},
				"status":           {"1"},
				"subscribe_status": {"1"},
				"subscribe_time":   {time.Unix(wechatUserInfo.SubscribeTime, 0).Format("2006-01-02 15:04:05")},
			}
			if inviteUser.Id > 0 {
				input["invite_user_id"] = []string{fmt.Sprintf("%d", inviteUser.Id)}
			}
			service.AddUser(input)
		}
	}
	e.Content = "关注"
	return e.HandleKeyword()
}

func (e *EventMsg) HandleKeyword() string {
	p := map[string]interface{}{}
	p["vagueKeyword"] = e.Content
	wechatReply := service.GetWechatReplyInfo(p)
	replyStr := "success"
	if wechatReply.Id > 0 {
		if wechatReply.Type == 1 { // 文本
			replyContent := ReplyText{}
			replyContent.ToUserName = e.FromUserName
			replyContent.FromUserName = e.ToUserName
			replyContent.CreateTime = time.Now().Unix()
			replyContent.MsgType = "text"
			replyContent.Content = wechatReply.Text
			xmlContent, _ := xml.Marshal(replyContent)
			replyStr = string(xmlContent)
		}
		if wechatReply.Type == 2 { // 图片
			img := ReplyPicImg{}
			img.MediaId = wechatReply.MediaId
			replyContent := ReplyPic{}
			replyContent.ToUserName = e.FromUserName
			replyContent.FromUserName = e.ToUserName
			replyContent.CreateTime = time.Now().Unix()
			replyContent.MsgType = "image"
			replyContent.Image = img
			xmlContent, _ := xml.Marshal(replyContent)
			replyStr = string(xmlContent)
		}
	}
	return replyStr
}

func (e *EventMsg) HandleClickKeyword() string {
	p := map[string]interface{}{}
	p["vagueKeyword"] = e.EventKey
	wechatReply := service.GetWechatReplyInfo(p)
	replyStr := "success"
	if wechatReply.Id > 0 {
		if wechatReply.Type == 1 { // 文本
			replyContent := ReplyText{}
			replyContent.ToUserName = e.FromUserName
			replyContent.FromUserName = e.ToUserName
			replyContent.CreateTime = time.Now().Unix()
			replyContent.MsgType = "text"
			replyContent.Content = wechatReply.Text
			xmlContent, _ := xml.Marshal(replyContent)
			replyStr = string(xmlContent)
		}
		if wechatReply.Type == 2 { // 图片
			img := ReplyPicImg{}
			img.MediaId = wechatReply.MediaId
			replyContent := ReplyPic{}
			replyContent.ToUserName = e.FromUserName
			replyContent.FromUserName = e.ToUserName
			replyContent.CreateTime = time.Now().Unix()
			replyContent.MsgType = "image"
			replyContent.Image = img
			xmlContent, _ := xml.Marshal(replyContent)
			replyStr = string(xmlContent)
		}
	}
	return replyStr
}
